package jwt

import (
	"bestcore/common/response"
	"crypto/rand"
	"crypto/rsa"

	"github.com/gofiber/fiber/v2"
	jwtware "github.com/gofiber/jwt/v3"
	"github.com/golang-jwt/jwt/v4"
)

var privateKey *rsa.PrivateKey
var middleware func(*fiber.Ctx) error

func GetPrivateKey() *rsa.PrivateKey {
	return privateKey
}
func GetMiddleware() func(*fiber.Ctx) error {
	return middleware
}
func GetToken(data jwt.MapClaims) (string, error) {
	token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, data).SignedString(privateKey)
	if err != nil {
		return "", err
	}
	return token, nil
}
func GetClaims(c *fiber.Ctx) map[string]interface{} {
	user := c.Locals("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	return claims
}

func Init() error {
	rng := rand.Reader
	var err error
	privateKey, err = rsa.GenerateKey(rng, 2048)
	if err != nil {
		return err
	}
	middleware = jwtware.New(jwtware.Config{
		SigningMethod: "RS256",
		SigningKey:    privateKey.Public(),
		ErrorHandler:  func(c *fiber.Ctx, err error) error { return response.Fail(c, err.Error()) },
	})
	return nil
}
